package com.css.fxfzypg.modules.baseData.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.entity.AreaEntity;
import com.css.fxfzypg.modules.baseData.queryParams.AreaQueryParams;
import com.css.fxfzypg.modules.baseData.repository.AreaRepository;
import com.css.fxfzypg.modules.baseData.service.AreaSevice;
import com.css.fxfzypg.util.FileUtil;
import com.css.fxfzypg.util.PlatformPageUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author y1fan
 * @create 2022-08-10 14:10
 */
@Service
public class AreaSeviceImpl implements AreaSevice {

    @Resource
    private AreaRepository areaRepositpry;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AreaEntity updateArea(AreaEntity areaEntity) {
        return    areaRepositpry.updateArea(areaEntity);
    }

    @Override
    public JSONObject findArea(AreaQueryParams areaQueryParams) {
        return PlatformPageUtils.formatPageData(areaRepositpry.findArea(areaQueryParams));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteArea(String areaId) {
        areaRepositpry.deleteAreaById(areaId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addArea(AreaEntity areaEntity) {
        areaEntity.setAreaId(UUIDGenerator.getUUID());
        areaEntity.setIsDelete(YNEnum.N.toString());
        areaRepositpry.addArea(areaEntity);
    }

    @Override
    public AreaEntity findByAreaId(String areaId) {
        return areaRepositpry.findByAreaid(areaId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteManyArea(List<String> ids) {
        areaRepositpry.deleteManyArea(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exportExcel(HttpServletResponse response)throws IOException {
        List<AreaEntity> list = areaRepositpry.exportExcel();
        FileUtil.exportExcel(list, "行政区划数据表", "sheet", AreaEntity.class, "AreaExcel", response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file)throws IOException {
        List<AreaEntity> areaEntities = FileUtil.importExcel(file, AreaEntity.class);
        for (AreaEntity areaEntity : areaEntities) {
            areaEntity.setAreaId(UUIDGenerator.getUUID());
            areaEntity.setIsDelete(YNEnum.N.toString());
        }
        areaRepositpry.importExcel(areaEntities);
    }
}
